package ru.spb.osll.myfit.client.widget;

import ru.spb.osll.myfit.client.Mode;
import ru.spb.osll.myfit.common.PageElement;
import ru.spb.osll.myfit.common.PageElementType;
import ru.spb.osll.myfit.common.WikiText;

import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class WikiTextWidget extends PageElementWidget {

	private WikiText m_wikiText;
	private VerticalPanel m_panel;
	private TextArea m_textArea;
	private int widthPadding = 3;

	public WikiTextWidget(GWTWidgetFactory gwtWidgetFactory, WikiText wikiText) {
		super(gwtWidgetFactory);
		m_wikiText = wikiText;

		sinkEvents(Event.ONMOUSEUP | Event.ONDBLCLICK | Event.ONCONTEXTMENU);
		createPopupMenu();
		initWidget(createViewWidget());
		m_mode = Mode.EDIT;
	}

	private Widget createViewWidget() {
    m_panel = m_gwtWidgetFactory.createVerticalPanel();
    m_panel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
    m_textArea = m_gwtWidgetFactory.createTextArea(m_wikiText.getWikiText());
    setMode(m_mode);
    m_panel.add(m_textArea);
    return m_panel;
  }

	private void autoSize() {
		String[] lines = m_textArea.getText().split("\n");
		int width = 0;
		for(String line: lines) {
			if(line.length() > width) {
				width = line.length();
			}
		}
		m_textArea.setVisibleLines(lines.length + 1);
		m_textArea.setCharacterWidth(width + widthPadding);
	}

	@Override
	public PageElement getPageElement() {
		if (!m_textArea.getText().equals(m_wikiText.getWikiText())) {
			m_wikiText.setText(m_textArea.getText(), m_textArea.getText());
			autoSize();
		}
		return m_wikiText;
	}

	@Override
	public void setOpen(boolean isOpen) {

	}

	@Override
	public PageElementType getType() {
		return PageElementType.WIKI_TEXT;
	}

	@Override
	public void setMode(Mode mode) {
    m_textArea.setReadOnly(mode == Mode.VIEW);
    if (mode == Mode.VIEW)
      m_textArea.addStyleName("wikiTextWidgetViewMode");
    else
      m_textArea.removeStyleName("wikiTextWidgetViewMode");

		autoSize();
		super.setMode(mode);
	}

}
